﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Configuration;

namespace wnet.admin
{
    public class MyTcpClient
    {
        private string serverIp = ConfigurationManager.AppSettings["IP"];

        Socket socketClient = null;

        Thread threadClient = null;

        private bool flag = true;

        public MyTcpClient()
        {
            var t1 = new Thread(() => Connect());
            t1.Start();
        }

        private void Connect()
        {
            try
            {
                socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ipaddress = IPAddress.Parse(serverIp);
                IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse("6001"));
                socketClient.Connect(endpoint);
                threadClient = new Thread(RecMsg);
                threadClient.IsBackground = true;
                threadClient.Start();
            }
            catch (Exception)
            {
                Thread.Sleep(10000);
                Connect();
            }
        }


        /// <summary>
        /// 接收服务端发来信息的方法
        /// </summary>
        private void RecMsg()
        {
            try
            {
                while (true) //持续监听服务端发来的消息
                {
                    byte[] arrServerRecMsg = new byte[65535];
                    int length = socketClient.Receive(arrServerRecMsg);
                    if (length > 0)
                    {
                        byte[] revByte = new byte[length];
                        Array.Copy(arrServerRecMsg, revByte, length);
                        ConstDefine.mSensorBusiness.AddProcessObj(revByte);
                        ConstDefine.mSensorAlarmBusiness.AddProcessObj(revByte);
                    }
                    else
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

